package com.travel.Service.Impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.travel.Bean.Trade;
import com.travel.Config.AliPayConfig;
import com.travel.JPA.TradeJPA;
//import com.zhixi.aliyunpay.util.OrderUtil;
import com.travel.util.Alipay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Service
public class AlipayServiceImpl {

    @Autowired
    private TradeJPA tradeJPA;
    @Autowired
    private RecordServiceImpl trecordService;

    public void payController(HttpServletResponse response, Alipay alipay) throws IOException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAYURL, AliPayConfig.APP_ID, AliPayConfig.MERCHANT_PRIVATE_KEY, "json", AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AliPayConfig.return_url);
        alipayRequest.setNotifyUrl(AliPayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(alipay.getOrderNumber().getBytes("ISO-8859-1"), "UTF-8");
        //付款金额，必填
        String total_amount = new String(alipay.getTotalAmount().getBytes("ISO-8859-1"), "UTF-8");
        //订单名称，必填
        String subject = new String(alipay.getTradeName().getBytes("ISO-8859-1"), "UTF-8");
        //商品描述，可空
        String body = alipay.getDescribe();

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String form = "";

        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        response.setContentType("text/html;charset=" + AliPayConfig.CHARSET);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();

    }


    public void AliPayNotify(HttpServletRequest request,HttpServletResponse response){
        try {

            //支付宝公钥
            String alipay_public_key= AliPayConfig.ZFB_PUBLIC_ID;
            PrintWriter out;
            out = response.getWriter();
            //获取支付宝POST过来反馈信息
            Map<String, String> params = new HashMap<String, String>();
            Map requestParams = request.getParameterMap();
            //循环遍历支付宝请求过来的参数存入到params中
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            //异步验签：切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
            boolean flag = AlipaySignature.rsaCheckV1(params, alipay_public_key, "utf-8","RSA2");
            if (flag){
                //说明是支付宝调用的本接口
                if (params.get("trade_status").equals("TRADE_SUCCESS") || params.get("trade_status").equals("TRADE_FINISHED")) {
                    System.out.println("收到回调结果，用户已经完成支付");
                    /***
                     * 这里写您的业务逻辑代码
                     */
                    String orderID = params.get("out_trade_no");

                    Trade trade = tradeJPA.getTradeByOrder_id(orderID);
                    //记录支付宝交易号
                    trade.setTrade_on(params.get("trade_no"));
                    //修改下单时的总金额，改为实际收款金额
                    trade.setReceipt_amount(Float.parseFloat(params.get("receipt_amount")));
                    //记录用户交易时间
                    trade.setTrade_time(Date.valueOf(params.get("gmt_payment")));
                    //保存订单信息
                    tradeJPA.save(trade);
                    //修改门票状态
                    trecordService.UpdateTrecord_1(orderID);

                    out.write("success");
                }
            }else {
                //验签失败该接口被别人调用
                out.write("支付宝异步回调验签失败，请留意");
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}